<template>
  <section class="todoapp">
    <!-- 头部 -->
    <ListHeader @headerContent="headerContent"></ListHeader>

    <!-- 内容 -->
    <ListBody
      :list="readerList"
      @change="change"
      @delList="delList"
      @event="event"
    ></ListBody>

    <!-- 底部 -->
    <ListFooter
      :sum="sum"
      :type="type"
      @changeType="changeType"
      @delBtn="delBtn"
      :showBtn="showBtn"
    ></ListFooter>
  </section>
</template>

<script>
import ListHeader from './components/ListHeader.vue'
import ListBody from './components/ListBody.vue'
import ListFooter from './components/ListFooter.vue'

export default {
  components: {
    ListHeader,
    ListBody,
    ListFooter,
  },

  data() {
    return {
      list:JSON.parse(localStorage.getItem('list')) || [
        {
          flag: true,
          id: 1,
          value: '读万卷书',
        },
        {
          flag: false,
          id: 2,
          value: '行万里路',
        },
      ],
      type: 'all',
    }
  },

  methods: {
    // 渲染页面
    headerContent(value) {
      this.list = [
        ...this.list,
        {
          flag: false,
          id: +new Date(),
          value: value,
        },
      ]
    },

    change(id, e) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag = e
      })
    },

    // 删除内容事件
    delList(id) {
      this.list = this.list.filter((item) => {
        return item.id !== id
      })
    },

    // 选中框事件
    changeType(type) {
      this.type = type
    },

    // 删除已完成事件
    delBtn() {
      this.list = this.list.filter((item) => {
        return !item.flag
      })
    },

    // 全选事件
    event(flag) {
      this.list.forEach((item) => {
        item.flag = flag
      })
    },
  },

  computed: {
    // 筛选状态为false的数组长度作为剩余数量
    sum() {
      return this.list.filter((item) => {
        return item.flag === false
      }).length
    },

    // 底部状态的内容
    readerList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },

    // 有未完成时隐藏
    showBtn() {
      return this.list.some((item) => {
        return item.flag
      })
    },
  },

// 深度监听
  watch: {
    immediate: true,
    deep: true,
    list: {
      handler(newValue) {
        localStorage.setItem('list', JSON.stringify(newValue))
      },
    },
  },
}
</script>

<style></style>
